/****************************************************
          File Name:udpse.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 26 Jan 2015 03:56:21 PM CST
*****************************************************/

#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/ip.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<assert.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>

#define SA  struct sockaddr
static socklen_t len = sizeof(struct sockaddr_in);

static void err(const char *s)
{
    perror(s);
    exit(errno);
}

int main(int argc, char *argv[])
{
    struct sockaddr_in client, server;
    int sockfd, fd;
    struct stat f_stat;

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
        err("socket");

    bzero(&server, len);
    bzero(&client, len);

    server.sin_family = AF_INET;
    inet_pton(AF_INET, "0", &server.sin_addr.s_addr);
    server.sin_port = htons(8888);

    if(bind(sockfd, (SA *)&server, len) == -1)
        err("bind");

    char name[20];
    bzero(&name, 20);

    recvfrom(sockfd, name, 20, 0, (SA *)&client, &len);     // get filename

    fd = open(name, O_RDONLY);
    if(fd == -1)
        err("open");

    fstat(fd, &f_stat);

    char size[20];
    sprintf(size, "%ld",f_stat.st_size);
    sendto(sockfd, size, 20, 0, (SA *)&client, len);

    char buffer[32765];
    char rev[1];

    while(read(fd, buffer, 32765))
    {
        if(sendto(sockfd, buffer, 32765, 0, (SA *)&client, len) == -1)
            err("sendto");
        if(recvfrom(sockfd, rev, 1, 0, NULL, 0) == -1) // get respond from client
            err("sendto");
    }
    close(fd);

    printf("---------done----------\n");
}
